package com.gallop.mq.core.codec;

import com.google.gson.Gson;
import com.gallop.mq.core.MQMessage;
import com.gallop.mq.core.MQMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class GsonMessageCodec implements MQMessageCodec {

    private final Gson gson = new Gson();

    @Override
    public byte[] encode(Object message) {
        if (message == null) {
            return new byte[0];
        }
        MQMessage msg = new MQMessage();
        msg.setClazz(message.getClass().getName());
        msg.setData(gson.toJson(message));
        return gson.toJson(msg).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public Object decode(byte[] raw) {
        String rawString = new String(raw, StandardCharsets.UTF_8);
        MQMessage message = gson.fromJson(rawString, MQMessage.class);
        if (message == null) {
            return null;
        }
        try {
            Class<?> clazz = Class.forName(message.getClazz());
            return gson.fromJson(message.getData(), clazz);
        } catch (Exception e) {
            log.error("decoding error:", e);
        }
        return null;
    }
}
